package file_service

import (
	"context"
	"errors"
	"io"
	"mime/multipart"
	"myserver/app/model"
	"myserver/app/types"
	"myserver/pkg/global"
	"myserver/pkg/utils"
	"time"
)

type FileService struct {
	File     *multipart.File
	Filename string
	Size     int64
}

func (p FileService) Save() (string, error) {

	tstr := utils.GetExtension(p.Filename)
	uuid := utils.GetUuid()
	path := global.CONFIG.Cos.Path + uuid + "." + tstr
	c := global.COS
	_, err := c.Object.Put(context.Background(), path, *p.File, nil)
	if err != nil {
		return "", err
	}

	m := types.SysFile{}
	m.Path = path
	m.Name = p.Filename
	m.Size = p.Size
	m.Suffix = "." + tstr
	m.Uuid = uuid
	err = model.AddFile(&m)
	if err != nil {
		return "", err
	}
	return m.Uuid, nil
}

func (FileService) GetFile(strs []string) (string, string, error) {
	var s string
	fileDbDatas, err := model.FindFileByUuid(strs)
	if err != nil {
		return s, "", err
	}
	if len(fileDbDatas) <= 0 {
		return s, "", errors.New("未查询到文件")
	}
	fileDbData := fileDbDatas[0]
	c := global.COS
	res, err := c.Object.Get(context.Background(), fileDbData.Path, nil)
	defer res.Body.Close()
	if err != nil {
		return s, "", err
	}

	bs, _ := io.ReadAll(res.Body)
	return string(bs), fileDbData.Name, nil

}
func (FileService) List(page int, size int, key string) ([]types.SysFile, int64, error) {
	return model.GETList[types.SysFile](page, size, "name", key)
}

func (FileService) DellFile(uuids []string) error {
	filelList, err := model.FindFileByUuid(uuids)
	l := len(filelList)
	if err != nil {
		return err
	}
	if l == 0 {
		return errors.New("为查询到数据")
	}
	for i := 0; i < len(filelList); i++ {
		filelList[i].IsDel = 1
		filelList[i].DeleTime = time.Now()
		/*
		 是否真实删除文件 目前软删除记录，保留文件
		*/
		// defer global.COS.Object.Delete(context.Background(), filelList[i].Path)
	}
	model.UpDataFiles(&filelList)
	return nil
}
